<!-- 
  select下拉框及级联选择组件                 zls-2022/06/01
    所有属性、事件、方法、插槽，请参考  https://vant-contrib.gitee.io/vant/#/zh-CN/picker

  Attributes
    1、hasFather  是否存在关联的上级内容，上级不选，该项不可选，用于给出提示（默认为false）
  Events
    1、confirm    必写
    2、clear      必写
 -->
<template>
  <Field
    class="z-input"
    v-model="data"
    :name="$attrs['name']"
    :label="$attrs['label']"
    :required="$attrs['required']"
    :rules="$attrs['required'] || $attrs['required'] === '' ? [{ required: true, message: '请选择' }] : []"
    :placeholder="$attrs['placeholder'] || '请选择'"
    :disabled="$attrs['disabled']"
    :readonly="$attrs['readonly'] || true"
    :border="$attrs['border']"
    :colon="$attrs['colon']"
    :clickable="$attrs['clickable']"
    :is-link="$attrs['is-link'] || true"
    :label-width="$attrs['label-width']"
    :autocomplete="$attrs['autocomplete']"
    @click="open"
  >
    <template #left-icon>
      <slot name="left-icon"></slot>
    </template>
    <template #right-icon>
      <z-svg name="chahao" v-if="data" @click.stop="clear"></z-svg>
    </template>
    <template #button>
      <slot name="button"></slot>
    </template>
    <template #extra>
      <slot name="extra"></slot>
    </template>
  </Field>

  <Popup
    v-model:show="show"
    :overlay="$attrs['overlay']"
    :position="$attrs['position'] || 'bottom'"
    :lock-scroll="$attrs['lock-scroll']"
    :close-on-click-overlay="$attrs['close-on-click-overlay']"
    :closeable="$attrs['closeable']"
    :close-icon="$attrs['close-icon']"
    :close-icon-position="$attrs['close-icon-position']"
    :safe-area-inset-bottom="true"
    round
    close-on-popstate
    @click-overlay="show = false"
    @click-close-icon="show = false"
  >
    <Picker
      :columns="$attrs['columns']"
      :columns-field-names="$attrs['columns-field-names']"
      :title="$attrs['title']"
      :loading="$attrs['loading']"
      :show-toolbar="$attrs['show-toolbar'] === false ? false : true"
      :readonly="$attrs['readonly']"
      :default-index="$attrs['default-index']"
      :class="{ isCascader: isCascader }"
      @confirm="confirm"
      @cancel="show = false"
    />
  </Popup>
</template>

<script>
export default { name: 'z-select' }
</script>
<script setup>
import { ref, useAttrs, watch } from 'vue'
import { Field, Popup, Picker, Toast } from 'vant'
import { getType } from '@/utils'
const emit = defineEmits(['update:modelValue', 'clear', 'confirm'])
const props = defineProps({
  // 格式必须为{ text: '', code: null }
  modelValue: {
    type: Object,
    default: () => ({})
  },
  hasFather: {
    type: Boolean,
    default: false
  }
})

const attrs = useAttrs()
const data = ref('')
const show = ref(false) // 是否显示弹框

const isCascader = ref(attrs.columns.length && attrs.columns[0].children ? true : false) // 是否是级联选择器（需要它判断逻辑和改变样式）

// 实时更新数据
watch(
  () => props.modelValue,
  newVal => {
    data.value = newVal.text
  },
  { immediate: true, deep: true }
)

function open() {
  if (attrs['readonly'] && props.hasFather) {
    Toast('请选择上级内容')
    return
  }
  show.value = true
}

// 清空
function clear() {
  const value = isCascader.value ? { text: '', code: null } : { text: '', code: '' }
  console.log(8989, value)
  emit('update:modelValue', value)
  emit('clear', value)
}

// 选中某一项后，点击确认按钮 { value:当前项的信息，index: 当前项的索引 }
// 如果返回的值是一个对象，说明是下拉框；如果返回的值是一个数组，说明是级联框；
function confirm(value, index) {
  let params
  if (getType(value) === 'array') {
    let code = [],
      text = []
    value.forEach((v, i) => {
      if (i !== 0) {
        code.push(v.code)
        text.push(v.text)
      }
    })
    params = { text: text.join(), code }
    data.value = text.join()
  } else {
    params = value
    data.value = value.text
  }
  show.value = false
  emit('update:modelValue', params)
  emit('confirm', params, index)
}
</script>
